package com.example.operation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.operation.domin.DispatchCondition;
import com.example.operation.dto.DispatchConditionDto;
import com.example.operation.mapper.DispatchConditionMapper;
import com.example.operation.service.DispatchConditionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @ClassName: DispatchConditionServiceImpl
 * @Description:
 * @Author
 * @Date 2021/11/24
 * @Version 1.0
 */


@Service
public class DispatchConditionServiceImpl extends ServiceImpl<DispatchConditionMapper, DispatchCondition> implements DispatchConditionService {

    @Autowired
    private DispatchConditionMapper dispatchConditionMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer update(DispatchConditionDto dispatchConditionDto) {
        DispatchCondition dispatchCondition = new DispatchCondition();
        LambdaUpdateWrapper<DispatchCondition> eq = new UpdateWrapper<DispatchCondition>()
                .lambda().eq(DispatchCondition::getAddress,dispatchConditionDto.getAddress());
        Integer count = dispatchConditionMapper.selectCount(eq);
        if(count == 0){
            throw new RuntimeException("您输入的配送地区不存在,请确认正确后重新输入");
        }
        BeanUtils.copyProperties(dispatchConditionDto,dispatchCondition);
        dispatchCondition.setAddress(dispatchConditionDto.getAddress().toString());
        return dispatchConditionMapper.update(dispatchCondition,eq);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insert(DispatchConditionDto dispatchConditionDto) {
        DispatchCondition dispatchCondition = new DispatchCondition();
        LambdaQueryWrapper<DispatchCondition> eq = new QueryWrapper<DispatchCondition>()
                .lambda().eq(DispatchCondition::getAddress,dispatchConditionDto.getAddress());
        Integer count = dispatchConditionMapper.selectCount(eq);
        if(count > 0){
            throw new RuntimeException("配送地区不能重复");
        }
        BeanUtils.copyProperties(dispatchConditionDto,dispatchCondition);
        dispatchCondition.setAddress(dispatchConditionDto.getAddress().toString());
        dispatchConditionMapper.insert(dispatchCondition);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer delectById(Integer id) {
        return dispatchConditionMapper.deleteById(id);
    }
}
